package file.tcp;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class TcpServer {

	public static void main(String[] args) throws IOException  {
		// TODO Auto-generated method stub
		//open port
		ServerSocket ss=new ServerSocket(8887);
		Socket acceptS=ss.accept();  //open port action
		System.out.println("server connection............");
		OutputStream os=acceptS.getOutputStream();
		InputStream is=acceptS.getInputStream();
		BufferedReader bufR=new BufferedReader(new InputStreamReader(is));
		os.write("Input the file name you want to get!\n".getBytes());
		String path="";
		while((path=bufR.readLine())!=null)
		{
			System.out.println("client want file: "+path);
			BufferedReader fileInput = null;
			try {
				fileInput = new BufferedReader(new InputStreamReader((new FileInputStream(path))));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				os.write("not found file\n".getBytes());
				continue;
			}
			os.write("file found\n".getBytes());
			String output="";
			while((output=fileInput.readLine())!=null)
			{
				os.write(output.getBytes());
				os.write("\n".getBytes());
			}
			os.write("file end\n".getBytes());
		}
		os.close();
		bufR.close();
		System.out.println();
	}

}
